package net.knightwatch.kwtools.walkthrough.items;

import java.util.ArrayList;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;

public class SpinnerAnswer extends Answer {
	private static final String TAG = "PickListAnswer";
	private ArrayList<String> possibleAnswers;
	private String answer;
	private int optionId;
	private Spinner spinner;
	private ArrayAdapter<String> spinnerArrayAdapter;
		
	public SpinnerAnswer(){
		this.setAnswerTypeId(SPINNER_TYPE);
		setPossibleAnswers(new ArrayList<String>());
		getPossibleAnswers().add("Select One");
	}

	public ArrayList<String> getPossibleAnswers() {
		return possibleAnswers;
	}

	public void setPossibleAnswers(ArrayList<String> possibleAnswers) {
		this.possibleAnswers = possibleAnswers;
	}

	@Override
	public LinearLayout getAnswerLayout(Context context) {
		LinearLayout linearLayout = new LinearLayout(context);
		spinner = new Spinner(context);
		// Application of the Array to the Spinner
		spinnerArrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, this.getPossibleAnswers());
		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
		spinner.setAdapter(spinnerArrayAdapter);
		spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){

			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		        Object item = parent.getItemAtPosition(pos);
		        Log.d(TAG, "Selected from spinner " + item.toString());
		        setAnswer(item.toString());
		        // FIXME Send the actual option ID from the database for historical purposes.
		        setOptionId(pos);
		    }

			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
			
		});
		linearLayout.addView(spinner);
		return linearLayout;
	}
	private void setOptionId(int pos) {
		this.optionId = pos;
	}
	@Override
	public String toString() {
		// Return the picklist value back as a string 
		return getAnswer();
	}

	public String getAnswer() {
		return this.answer;
	}

	public void setAnswer(String answer) {
		this.answer = answer;
	}

	public int getOptionId() {
		return optionId;
	}

	@Override
	public void updateAnswerView() {
		// TODO Remove?
		
	}

	@Override
	public void setAnswerText(String answerText) {
		// TODO Update the spinner answer
		this.answer = answerText;
		for(int i = 0; i < spinnerArrayAdapter.getCount(); i++){
			String answer = spinnerArrayAdapter.getItem(i);
			Log.d(TAG, "TEST: " + answer + " = " + answerText);
			if(answer.equals(answerText)){
				Log.d(TAG, "Set spinner selected id to "+i);
				this.spinner.setSelection(i);
			}
			
		}
	}
}
